<template>
  <div class="app-container">
    <div class="header" style="display: flex;justify-content: space-between;">
      <el-form :inline="true" :model="query" class="demo-form-inline">
        <el-form-item label="角色名称">
          <el-input size="small" v-model="query.roleName" placeholder="角色名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="onSubmit">查询</el-button>
        </el-form-item>
      </el-form>
      <div class="right">
        <el-button type="danger" size="small" @click="batchDelete">批量删除</el-button>
        <el-button type="primary" size="small" @click="addRole">添加</el-button>
      </div>
    </div>

    <el-table
      v-loading="listLoading"
      @selection-change="handleSelectionChange"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column align="center" label="序号" width="95">
        <template slot-scope="scope">
          {{scope.$index+1}}
        </template>
      </el-table-column>
      <el-table-column label="角色名称"  align="center" prop="roleName"></el-table-column>
      <el-table-column label="角色编码"  align="center" prop="roleCode"></el-table-column>
      <el-table-column label="角色说明"  align="center" prop="description"> </el-table-column>
      <el-table-column class-name="status-col" label="创建时间" width="230" prop="createTime" align="center"></el-table-column>
      <el-table-column align="center" prop="created_at" label="操作" width="200">
        <template slot-scope="scope">
          <el-button icon="el-icon-edit" type="primary" @click=editRole(scope.row) size="mini"></el-button>
          <el-button icon="el-icon-delete" type="warning" @click="deleteRole(scope.row.id)" size="mini"></el-button>
          <el-button icon="el-icon-plus" type="success" @click="addMenu(scope.row)" size="mini"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="sizes,prev, pager, next"
      :page-sizes="[2,5,10,20]"
      :page-size="limit"
      @size-change="sizeChange"
      @current-change="currentChange"
      :total="total">
    </el-pagination>


<!--    弹窗-->
    <el-dialog title="角色" :visible.sync="dialogFormVisible">
      <el-form :model="form" label-width="120px" label-position="left">
        <el-form-item label="角色名称" ><el-input style="width: 90%;" v-model="form.roleName"  autocomplete="off"/></el-form-item>
        <el-form-item label="角色编码" ><el-input style="width: 90%;" v-model="form.roleCode" /></el-form-item>
        <el-form-item label="角色描述" ><el-input style="width: 90%;" type="textarea" :rows="2" v-model="form.description" /></el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitRole">确 定</el-button>
      </div>
    </el-dialog>

<!--    菜单选择-->
    <el-dialog title="菜单" :visible.sync="dialogFormMenuVisible" destroy-on-close>
      <el-tree
      :data="menuList"
      show-checkbox
      node-key="id"
      default-expand-all
      highlight-current
      ref="tree"
      :props="defaultProps">
    </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormMenuVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitMenu">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import api from '@/api/systemRole'
import menuApi from '@/api/systemMenu'

export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      list: null,
      listLoading: true,
      page:1,
      limit:10,
      query:{roleName:""},
      total:0,
      dialogFormVisible:false,
      dialogFormMenuVisible:false,
      multipleSelection:[],
      defaultChecked:[],
      form:{
        description:'',
        roleCode:'',
        roleName:'',
      },
      menuList:[],
      menuForm:{
        "menuIdList": [],
        "roleId": ""
      },
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  created() {
    this.fetchData();
    this.getMenuList();
  },
  methods: {
    async getMenuList() {
      this.menuList =await menuApi.getPageList();
    },
    resetForm(){
      this.form={
          description:'',
          roleCode:'',
          roleName:'',
      }
    },
    async submitMenu() {
      let menuList = this.$refs.tree.getCheckedKeys();
      console.log(menuList)
      this.menuForm.menuIdList = menuList;
      await api.doAssign(this.menuForm);
      this.$message({
        type: 'success',
        message: '修改成功!'
      });
      this.dialogFormMenuVisible=false;
    },
    submitRole(){
      if (this.form.id){
        api.updateRole(this.form).then(value => {
          console.log(value);
          this.$message({
            type: 'success',
            message: '修改成功!'
          });
          this.fetchData();
          this.dialogFormVisible=false;
        });
      }else {
        api.saveRole(this.form).then(value => {
          console.log(value);
          this.$message({
            type: 'success',
            message: '添加成功!'
          });
          this.fetchData();
          this.dialogFormVisible=false;
        });
      }
    },
    handleSelectionChange(val) {
      // console.log(val);
      this.multipleSelection= val.reduce((r,c)=>{
        return r.concat(c.id)
      },[])
    },
    async batchDelete() {
      if (!this.multipleSelection.length) {
        this.$message({
          type: 'error',
          message: '请先选择!'
        });
        return;
      }
      await api.batchRemove(this.multipleSelection);
      this.$message({
        type: 'success',
        message: '删除成功!'
      });
      this.fetchData();
    },
    addRole(){
      this.resetForm();
      this.dialogFormVisible=true;
    },
    editRole(row){
      this.addRole();
      this.form=JSON.parse(JSON.stringify(row));
    },
    sizeChange(val){
      this.page=1;
      this.limit=val;
      this.fetchData();
    },
    currentChange(val){
      this.page=val;
      this.fetchData();
    },
    onSubmit(){
      this.page=1;
      this.fetchData();
    },
    async addMenu(row) {
      let data = await api.toAssign(row.id);
      this.dialogFormMenuVisible = true;
      this.menuForm.roleId=row.id;
      this.$nextTick(()=>{
        this.$refs.tree.setCheckedKeys(data);
      })
    },
    deleteRole(id){
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await api.removeRole(id);
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
        this.fetchData();
      }).catch(() => {
      });
    },
    fetchData() {
      this.listLoading = true
      api.getPageList(this.page,this.limit,this.query).then(response => {
        this.list = response.records
        this.total= response.total
        this.listLoading = false
      })
    }
  }
}
</script>
